package com.sxj.corejava.code12_线程;

/**
 * @author 石小俊
 * @date 2025年02月25日
 */
public class Test08_死锁问题 {

    public static void main(String[] args) {
        Object obj1 = new Object();
        Object obj2 = new Object();
        A a = new A(obj1,obj2);
        B b = new B(obj1,obj2);

        a.start();
        b.start();
    }

}

class A extends Thread{
    private Object obj1;
    private Object obj2;

    public A(Object obj1, Object obj2) {
        this.obj1 = obj1;
        this.obj2 = obj2;
    }

    @Override
    public void run() {
        synchronized (obj1){
            System.out.println("A中获取到obj1的锁");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (obj2){
                System.out.println("等待B释放obj2,我才能执行");
            }
        }
    }
}

class B extends Thread{
    private Object obj1;
    private Object obj2;

    public B(Object obj1, Object obj2) {
        this.obj1 = obj1;
        this.obj2 = obj2;
    }

    @Override
    public void run() {
        synchronized (obj2){
            System.out.println("B中获取到obj2的锁");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (obj1){
                System.out.println("等待A释放obj1,我才能执行");
            }
        }
    }
}
